/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package checkers.database;

import checkers.businessLogic.entity.GameTable;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author artinshahverdian
 */
public class MySQLGameOperations implements IDatabaseGameOperations {

    private static MySQLGameOperations instance = null;
    private ConnectionPool connectionPool;

    private MySQLGameOperations() throws Exception {
        connectionPool = ConnectionPool.getInstance();
    }

    public static MySQLGameOperations GetInstance() throws Exception {
        if (instance == null)
            instance = new MySQLGameOperations();
        return instance;
    }

    @Override
    public void registerGameTable(GameTable gameTable) throws SQLException {
        int isGuest = 0;
        if (gameTable.getUserId2()==0){
            isGuest = 1;
        }
        Integer userId2 = null;
        
        if (!gameTable.isGuest()){
            userId2 = gameTable.getUserId2();
        }
        String query;
        if (gameTable.isGuest()){
         query = "INSERT INTO game_table (is_guest, winner, "
                + "creation_date, user_id1, "
                + " termination_date) VALUES "
                + "('" + isGuest+ "','" + gameTable.getWinner() + "','"
                + gameTable.getCreationDate() + "','" + gameTable.getUserId1() + "','"
                +  gameTable.getTerminationDate() + "');";
        }
        else{
              query = "INSERT INTO game_table (is_guest, winner, "
                + "creation_date, user_id1, user_id2,"
                + " termination_date) VALUES "
                + "('" + isGuest+ "','" + gameTable.getWinner() + "','"
                + gameTable.getCreationDate() + "','" + gameTable.getUserId1() + "','"
                + gameTable.getUserId2()+"','"+ gameTable.getTerminationDate() + "');";
            
        }

        executeUpdate(query);
    }

    private void executeUpdate(String query) throws SQLException {

        Connection connection = connectionPool.getConnection();
        Statement statement = connection.createStatement();

        try {
            statement.executeUpdate(query);
        }
        finally {
            connection.close();
            statement.close();
        }


    }
}
